package com.newland.starpos.partner.configuration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by liuNW on 2018/9/27.
 */
@EnableCaching
@Configuration
public class CacheConfiguration {

    private static final String keyPrefix = "PT_";

    @Bean
    @ConditionalOnBean(RedisTemplate.class)
    public void redisTemplate(RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
    }

    @Bean
    @ConditionalOnMissingBean(RedisCacheManager.class)
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){

        //默认配置
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofHours(1L)).prefixKeysWith(keyPrefix).disableCachingNullValues();

        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.builder(redisConnectionFactory);

        Map<String, RedisCacheConfiguration> cacheConfigurations = new LinkedHashMap<>();
        cacheConfigurations.put("user", defaultCacheConfig.entryTtl(Duration.ofHours(2)));

        builder.cacheDefaults(defaultCacheConfig).transactionAware().withInitialCacheConfigurations(cacheConfigurations);

        return builder.build();
    }
}
